<template>
  <div @keyup.enter="tosearchresult(searchEngines[0]!)" class="search">
    <n-auto-complete
      v-model:value="searchText"
      :input-props="{
        autocomplete: 'disabled',
      }"
      :options="textList"
      placeholder="搜索"
      clearable
      class="seach-input"
    >
      <template #suffix>
        <Icon icon="material-symbols:search" />
      </template>
    </n-auto-complete>
    <n-flex>
      <n-button
        round
        size="tiny"
        v-for="item in searchEngines"
        :key="item.name"
        @click="tosearchresult(item)"
      >
        {{ item.name }}
      </n-button>
    </n-flex>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Icon } from '@iconify/vue'
import searchEngines, { type SearchEngine } from '../assets/searchEngines'
import { isMobile } from '../utils'
import { http } from '@/utils/request'

const searchText = ref('')
const textList = ref([])
watch(searchText, (wd) => {
  http(`/baidu?prod=pc&wd=${wd}`).then((res: any) => {
    if (res.g) {
      textList.value = res.g.map((item: { q: any }) => ({ value: item.q, label: item.q }))
    }
  })
})

const router = useRouter()
function tosearchresult(e: SearchEngine) {
  if (isMobile) {
    location.href = (e.mobileurl || e.url) + searchText.value
  } else {
    router.push(`/searchresult?q=${searchText.value}&s=${e.param}`)
  }
}
</script>

<style lang="scss">
.search {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;

  .seach-input {
    width: 50%;
  }
}

@media screen and (max-width: 40rem) {
  .search .seach-input {
    width: 98%;
  }
}
</style>
